<!--
 * @Description: 公司标准产品配合比
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 14:24:00
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display:flex">
        <div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="formBox('添加产品配合比',false),fromDate.id=''">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                  添加
                </el-button>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark">
                <el-table-column type="index" label="序号" width="50">
                </el-table-column>
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width">
                    <template slot-scope="scope">
                      <el-button v-if="item.label == '配合比'&&ButtonList.findIndex(res=>(res.buttonValue=='CHAKAN'))!==-1" class="bottom_one" size="mini" @click="formBox('产品配合比',true,scope.row)">查看</el-button>
                      <div v-else-if="item.label =='操作'">
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="formBox('修改产品配合比',false,scope.row)">
                          修改</el-button>
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" class="bottom_two" size="mini" @click="deleteFun(scope.row)">
                          删除
                        </el-button>
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JILU'))!==-1" class="bottom_one" size="mini" @click="formBox('产品配合比',true,scope.row,true)">记录</el-button>
                      </div>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="look1Type" width="800px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div>
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="100px">
          <el-form-item prop="companyId">
            <span slot="label">公司</span>
            <el-select ref="selection1" v-model="fromDate.companyId" :disabled="jlType" placeholder="请选择" @change="$nextTick(()=>{fromDate.company = $refs.selection1.selectedLabel})">
              <el-option v-for="item in companylist" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="strengthGradeId">
            <span slot="label" style="color:#FF0000;">标号</span>
            <el-select v-model="fromDate.strengthGradeId" :disabled="disabledType ||jlType" placeholder="请选择">
              <el-option v-for="item in strengthGradeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="commencementDate">
            <span slot="label" style="color:#FF0000;">生效日期：</span>
            <el-select v-if="jlType" v-model="timeId" @change="queryDateListFun()">
              <el-option v-for="item in itemList" :key="item.id" :label="item.commencementDate" :value="item.id"></el-option>
            </el-select>
            <el-date-picker v-else v-model="fromDate.commencementDate" :disabled="disabledType" type="datetime" value-format="yyyy-MM-dd HH" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
        </el-form>
        <div>
          <span class="dialog-title">配合比</span>
          <el-button v-show="!disabledType" size="mini" class="bottom_all" style="margin-left: 12px;" @click="addItem()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
            添加
          </el-button>
        </div>
        <div style="padding-top:10px">
          <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="listArry" tooltip-effect="dark">
            <el-table-column label="原物料" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.rawId" :disabled="disabledType" placeholder="请选择" style="width: 100%;" @change="changeItem(scope.row,scope.$index)">
                  <el-option v-for="(item, index) in rawIdArry" :key="index" :label="item.itemName" :value="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="配合比值" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.ratioValue" :disabled="disabledType" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.ratioValue=$regExp.checkNum(scope.row.ratioValue)" @blur="scope.row.ratioValue=$regExp.blurCheckNum(scope.row.ratioValue)"></el-input>
              </template>
            </el-table-column>
            <el-table-column v-if="!jlType" label="操作" align="left" width="120">
              <template slot-scope="scope">
                <el-button v-show="!disabledType" size="mini" class="bottom_two" @click="deleteItem(scope.$index)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="look1TypeFun(false)">关 闭</el-button>
        <el-button v-show="!disabledType" class="bottom_all" style="margin-left: 24px;" @click="pagessubmitFromDate()">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-dialogDrag :visible.sync="look2Type" width="1015px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看详情</span>
      <div class="dialoginfo">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="listArry2" tooltip-effect="dark">
          <el-table-column label="原物料" align="center" prop="contractNo"></el-table-column>
          <el-table-column label="配合比值" align="center" prop="supplierName"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="look2Type=false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryList,
  saveOrUpdate,
  getLists,
  queryDetails,
  deletes,
  queryLogList,
  queryDateList
} from "@/api/basicConfig/companyStandard.js";
import { permissionsCompanyList, getDicType } from "@/api/common.js";
import { getUserInfo } from "@/utils/auth.js";

export default {
  mixins: [mixin],
  data() {
    return {
      /*表格数据*/
      table: [
        { label: "标号", width: "auto", prop: "strengthGrade", status: true },
        { label: "配合比", width: "100", prop: "", status: true },
        { label: "生效日期", width: "auto", prop: "commencementDate", status: true },
        { label: "操作", width: "260", prop: "", status: true, },
      ],
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        companyId: [
          { required: true, message: "请选择公司", trigger: "change" },
        ],
        strengthGradeId: [
          { required: true, message: "请选择标号", trigger: "change" },
        ],
        commencementDate: [
          { required: true, message: "请选择生效日期", trigger: "change" },
        ],
      },
      strengthGradeList: [],
      rawIdArry: [],
      fromDate: {
        companyId: '',
        strengthGradeId: "",
        commencementDate: "",
        list: [],
      },
      listArry: [],
      listArry2: [],
      look1Type: false,
      look2Type: false,
      disabledType: false,
      jlType: false,
      itemList: [],
      timeId: '',
      companylist: []
    };
  },
  async created() {
    this.companylist = await permissionsCompanyList()
    /*存储拷贝的原初始化fromDate数据*/
    this.getList()
    getLists().then((res) => {
      res.data.forEach((v) => {
        if (v.typeName == "强度等级") {
          this.strengthGradeList = v.list;
        }
      });
    });
    getDicType({
      code: "MATname",
    }).then((res) => {
      this.rawIdArry = res.data.items;
    });
  },
  methods: {
    deleteFun(e) {
      deletes({ id: e.id }).then((res) => {
        if (res.code == 1001) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.getList()
        }
      })
    },
    look1TypeFun(type) {
      let json = {
        strengthGradeId: "",
        commencementDate: "",
        list: [],
      }
      this.listArry = []
      this.fromDate = { ...this.fromDate, ...json }
      setTimeout(() => {
        this.$refs.reffromDate.clearValidate()
        this.look1Type = type
      }, 10)
    },
    /**name:表单标题， disabled：是否可操作，e：详情的参数，type:true不可操作*/
    formBox(name, disabled, e, type) {
      this.timeId = ''
      this.look1Type = true
      setTimeout(() => {
        this.$refs.reffromDate.resetFields();
        this.disabledType = disabled
        this.addDialogTitle = name
        if (this.addDialogTitle == '添加产品配合比') {

          let size = this.companylist.findIndex((res) => res.id == getUserInfo().companyId)
          if (size != -1) {
            this.fromDate.companyId = this.companylist[size].id
            this.fromDate.company = this.companylist[size].name
          }
        }
        if (e) {
          queryDetails({ id: e.id }).then((res) => {
            this.fromDate = res.data
            if (!type) {
              this.listArry = JSON.parse(JSON.stringify(this.fromDate.list))
            }
          })
        }
        this.jlType = false
        if (type) {
          this.jlType = true;
          queryLogList({ strengthGradeId: e.strengthGradeId, companyId: e.companyId }).then((res) => {
            this.itemList = res.data
            if (res.data[0]) {
              this.timeId = res.data[0].id
              this.$nextTick(() => { this.$refs.reffromDate.clearValidate() });
              this.queryDateListFun()
            }
          })
        }
      }, 100)
    },
    /**根据记录时间查询 配合比列表 */
    queryDateListFun() {
      queryDateList({ id: this.timeId }).then((res) => {
        this.listArry = res.data
      })
    },
    getList() {
      queryList({}).then((res) => {
        this.tableData = res.data
      })
    },
    /*添加*/
    addItem() {
      let item = {
        type: '1',
        rawId: "",
        rawName: "",
        ratioValue: "",
      };
      this.listArry.push(item);
    },
    changeItem(e, index) {
      let type = false
      this.listArry.forEach((v, k) => {
        if (v.rawId == e.rawId && k != index) {
          type = true
        }
      })
      if (type) {
        this.$message({
          message: '已选择该原物料',
          type: 'warning'
        });
        e.rawId = ''
      } else {
        e.rawName = this.$fromatTable(
          this.rawIdArry,
          e.rawId,
          "id",
          "itemName"
        );
      }
    },
    deleteItem(index) {
      this.listArry.splice(index, 1);
    },
    /**新增-修改*/
    pagessubmitFromDate() {
      this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          this.fromDate.strengthGrade = this.$fromatTable(
            this.strengthGradeList,
            this.fromDate.strengthGradeId,
            "id",
            "name"
          );
          let type = false
          this.listArry.forEach((v) => {
            if (v.rawId == '') {
              type = true
            }
          })
          if (type || this.listArry.length == 0) {
            this.$message({
              message: '数据不完整！',
              type: 'warning'
            });
            return
          }
          if (this.fromDate.list) {
            let update = this.listArry.filter((res) =>
              this.fromDate.list.some((item) => res.id == item.id)
            );
            update.forEach((res) => {
              res.type = 2;//修改的
            });
            let deleteData = this.fromDate.list.filter(
              (res) => !update.some((item) => res.id == item.id)
            );
            deleteData.forEach((res) => {
              res.type = 3; //3是删除
            });
            let addData = this.listArry.filter(
              //新增的type默认写死为 1
              (res) => !update.some((item) => res.id == item.id)
            );
            this.fromDate.list = [...update, ...deleteData, ...addData];
          } else {
            this.fromDate.lis = this.listArry
          }
          if (this.fromDate.commencementDate.length == 13) {
            this.fromDate.commencementDate = this.fromDate.commencementDate + ':00:00'
          }
          this.fromDate.company = this.$fromatTable(
            this.companylist,
            this.fromDate.companyId,
            "id",
            "name"
          );
          console.log(JSON.parse(JSON.stringify(this.fromDate)))
          saveOrUpdate(this.fromDate).then((res) => {
            if (res.code == 1001) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.look1Type = false
              this.getList()
            }
            this.list = res.data;
          });
          this.look1Type = true;
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-title {
  font-size: 16px;
  font-weight: bold;
  padding-right: 40px;
}
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
</style>
